package com.airlines.system.service.impl;

import com.airlines.system.dao.SysRoleMapper;
import com.airlines.system.dao.SysUserMapper;
import com.airlines.system.dao.SysUserRoleMapper;
import com.airlines.system.domain.SysRole;
import com.airlines.system.domain.SysUser;
import com.airlines.system.domain.SysUserRole;
import com.airlines.system.service.SysRoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService{

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public List<SysRole> findAll() {
        return sysRoleMapper.findAll();
    }

    @Override
    public List<SysRole> findAllByType(String typeId) {
        return sysRoleMapper.findAllByType(typeId);
    }

    @Override
    public SysRole findOne(String roleId) {
        return sysRoleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public List<SysUser> findUsersByRoleId(String roleId) {
        // 查询 t_sys_user_role
        List<SysUserRole> userRoleList = sysUserRoleMapper.findByRoleId(roleId);
        if (userRoleList == null || userRoleList.size() == 0) {
            List<SysUser> users = new ArrayList<>();
            return users;
        }

        //定义一个list接收符合条件的userId
        List<String> userIds = new ArrayList<>();
        for (SysUserRole userRole : userRoleList) {
            userIds.add(userRole.getUserId());
        }
        // 查询 t_sys_user
        return sysUserMapper.findByIds(userIds);
    }
   /*
    @Autowired
    private SysRoleTypeMapper sysRoleTypeMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysRoleFuncMapper sysRoleFuncMapper;*/

   /* @Autowired
    private DhAirOaApiService dhAirOaApiService;

    @Override
    public List<SysRole> findAllSysRole(String typeId) {
        SysRoleTypeExample roleTypeExample = new SysRoleTypeExample();
        SysRoleTypeExample.Criteria criteria = roleTypeExample.createCriteria();
        criteria.andTypeIdEqualTo(typeId);
        List<SysRoleType> sysRoleTypes = sysRoleTypeMapper.selectByExample(roleTypeExample);

        if (sysRoleTypes == null || sysRoleTypes.size() == 0) {
            List<SysRole> roles = new ArrayList<>();
            return roles;
        }
        //定义一个list接收符合条件的roleId
        List<String> roleIds = new ArrayList<>();
        for (SysRoleType roleType : sysRoleTypes) {
            roleIds.add(roleType.getRoleId());
        }
        // 查询 t_sys_role
        SysRoleExample roleExample = new SysRoleExample();
        SysRoleExample.Criteria exampleCriteria = roleExample.createCriteria();
        exampleCriteria.andIdIn(roleIds);
        exampleCriteria.andStatusEqualTo(1);
        return sysRoleMapper.selectByExample(roleExample);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRole(String typeId, SysRole sysRole) {
        // 判断该系统角色名称是否重复
        List<SysRole> list = sysRoleMapper.findRoleByType(typeId, sysRole.getRoleName());
        if (list != null && list.size() > 0) {
            throw new ServiceException(ErrorConst.ERROR_CODE_UNKNOWN_ERROR, "该类型的角色已存在");
        }
        // insert t_sys_role
        sysRole.setId(UUID.randomUUID().toString());
        sysRoleMapper.insertSelective(sysRole);
        // insert into t_sys_role_type
        SysRoleType roleType = new SysRoleType();
        roleType.setId(UUID.randomUUID().toString());
        roleType.setRoleId(sysRole.getId());
        roleType.setTypeId(typeId);
        return sysRoleTypeMapper.insertSelective(roleType) > 0 ? true : false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(String roleId) {
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(roleId);
        if (sysRole == null) {
            throw new ServiceException(ErrorConst.ERROR_CODE_UNKNOWN_ERROR, "该角色数据不存在");
        }
        //删除 t_sys_role_type
        SysRoleTypeExample roleTypeExample = new SysRoleTypeExample();
        SysRoleTypeExample.Criteria roleTypeCriteria = roleTypeExample.createCriteria();
        roleTypeCriteria.andRoleIdEqualTo(roleId);
        sysRoleTypeMapper.deleteByExample(roleTypeExample);
        //删除 t_sys_role_menu对应的记录
        SysRoleMenuExample roleMenuExample = new SysRoleMenuExample();
        SysRoleMenuExample.Criteria roleMenuCriteria = roleMenuExample.createCriteria();
        roleMenuCriteria.andRoleIdEqualTo(roleId);
        sysRoleMenuMapper.deleteByExample(roleMenuExample);
        //删除 t_sys_role_function
        SysRoleFuncExample roleFuncExample = new SysRoleFuncExample();
        SysRoleFuncExample.Criteria roleFuncCriteria = roleFuncExample.createCriteria();
        roleFuncCriteria.andRoleIdEqualTo(roleId);
        sysRoleFuncMapper.deleteByExample(roleFuncExample);
        //删除t_sys_user_role记录
        SysUserRoleExample userRoleExample = new SysUserRoleExample();
        SysUserRoleExample.Criteria userRoleCriteria = userRoleExample.createCriteria();
        userRoleCriteria.andRoleIdEqualTo(roleId);
        sysUserRoleMapper.deleteByExample(userRoleExample);
        //删除t_sys_role记录
        sysRoleMapper.deleteByPrimaryKey(roleId);
        return true;
    }

    @Override
    public SysRole findOneRoleWithMenus(String roleId) {
        return sysRoleMapper.findOneRoleWithMenus(roleId);
    }



    @Override
    public void deleteUserRoleByRoleIdAndUserId(String roleId, String userId) {
        sysUserRoleMapper.deleteUserRoleByUserIdAndRoleId(userId, roleId);
    }

    @Override
    public List<OaDepartmentDO> listDeptFromOA() {
        List<OaDepartmentDO> list = new ArrayList<>();

        Object obj = dhAirOaApiService.getOADepartment();
        try {
            if (obj != null && obj instanceof JSONObject) {
                JSONObject jsObj = (JSONObject) obj;
                if (jsObj.has("deptList")) {
                    JSONArray datas = jsObj.getJSONArray("deptList");
                    for (int i = 0; i < datas.length(); i++) {
                        JSONObject data = datas.getJSONObject(i);
                        OaDepartmentDO dept = jsonObj2DeptDO(data);
                        list.add(dept);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public List<SysUser> listDeptEmpFromOA(String deptId) {
        return listOAEmp(deptId, "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysUser> addUser2Role(String roleId, SysUser sysUser) {
        // 增加用户
        SysUser user = sysUserMapper.findByUserNo(sysUser.getWorkNo());
        if (user == null) {
            sysUser.setId(UUID.randomUUID().toString());
            sysUserMapper.insertSelective(sysUser);
            user = sysUser;
        }

        // 查找该用户是否已存在该角色
        SysUserRole sysUserRole = sysUserRoleMapper.findUserRoleByUserIdAndRoleId(user.getId(), roleId);
        if (sysUserRole != null && sysUserRole.getUserId() != null) {
            throw new ServiceException(ErrorConst.ERROR_CODE_UNKNOWN_ERROR, "该角色组已经存在该用户");
        }
        // 新增一条记录
        SysUserRole userRole = new SysUserRole();
        userRole.setId(UUID.randomUUID().toString());
        userRole.setRoleId(roleId);
        userRole.setUserId(user.getId());
        sysUserRoleMapper.insertSelective(userRole);

        return sysUserMapper.findSysUserByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysUser> addUsers2Role(String roleId, List<SysUser> sysUsers) {
        for (SysUser sysUser : sysUsers) {
            // 增加用户
            SysUser user = sysUserMapper.findByUserNo(sysUser.getWorkNo());
            if (user == null) {
                sysUser.setId(UUID.randomUUID().toString());
                sysUserMapper.insertSelective(sysUser);
                user = sysUser;
            }
            // 删除该用户的所属组
            sysUserRoleMapper.deleteUserRoleByUserIdAndRoleId(user.getId(), roleId);

            SysUserRole userRole = new SysUserRole();
            userRole.setId(UUID.randomUUID().toString());
            userRole.setRoleId(roleId);
            userRole.setUserId(user.getId());
            sysUserRoleMapper.insertSelective(userRole);
        }

        return sysUserMapper.findSysUserByRoleId(roleId);
    }

    @Override
    public List<SysUser> listEmpFromOAByNo(String workNo) {
        return listOAEmp("", workNo);
    }

    @Override
    @Transactional
    public SysRole editRight(String roleId, List<String> menuIds, List<SysFunc> funcList) {
        //insert t_sys_role_menu
        //先删除原先存在的
        SysRoleMenuExample example = new SysRoleMenuExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        sysRoleMenuMapper.deleteByExample(example);
        //批量插入
        for (String id : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(UUID.randomUUID().toString());
            sysRoleMenu.setMenuId(id);

            sysRoleMenu.setRoleId(roleId);
            sysRoleMenuMapper.insertSelective(sysRoleMenu);
        }
        //insert t_sys_role_function
        //先删除原先存在的
        List<SysRoleFunc> roleFunclist = new ArrayList<>();

        for (SysFunc sysFunc : funcList) {
            roleFunclist.add(new SysRoleFunc(UUID.randomUUID().toString(), roleId, sysFunc.getMenuId(), sysFunc.getId()));
            sysRoleFuncMapper.deleteByRoleIdAndfunId(roleId, sysFunc.getId());
        }
        sysRoleFuncMapper.batchSave(roleFunclist);

        SysRole sysRole = new SysRole();
        sysRole.setId(roleId);
        return sysRole;
    }

    @Override
    public List<SysRole> searchByRoleName(String roleName) {
        return sysRoleMenuMapper.findByLikeRoleName("%" + roleName + "%");
    }


    private OaDepartmentDO jsonObj2DeptDO(JSONObject obj) throws JSONException {
        OaDepartmentDO dept = new OaDepartmentDO();
        dept.setChildNode(new ArrayList<>());

        if (obj.has("code") && obj.get("code") != null) {
            dept.setCode(obj.getString("code"));
        }
        if (obj.has("companyName") && obj.get("companyName") != null) {
            dept.setCompanyName(obj.getString("companyName"));
        }
        if (obj.has("levelNum") && obj.get("levelNum") != null && !obj.get("levelNum").equals("")) {
            dept.setLevelNum(obj.getInt("levelNum"));
        }
        if (obj.has("sortNum") && obj.get("sortNum") != null && !obj.get("sortNum").equals("")) {
            dept.setSortNum(obj.getInt("sortNum"));
        }
        if (obj.has("id") && obj.get("id") != null) {
            dept.setId(obj.getString("id"));
        }
        if (obj.has("empCount") && obj.get("empCount") != null && !obj.get("empCount").equals("")) {
            dept.setEmpCount(obj.getInt("empCount"));
        }
        if (obj.has("description") && obj.get("description") != null) {
            dept.setDescription(obj.getString("description"));
        }
        if (obj.has("sts") && obj.get("sts") != null) {
            dept.setSts(obj.getString("sts"));
        }
        if (obj.has("name") && obj.get("name") != null) {
            dept.setName(obj.getString("name"));
        }
        if (obj.has("fatherId") && obj.get("fatherId") != null) {
            dept.setFatherId(obj.getString("fatherId"));
        }
        if (obj.has("deptId") && obj.get("deptId") != null) {
            dept.setDeptId(obj.getString("deptId"));
        }
        if (obj.has("childNode") && obj.get("childNode") != null) {
            Object childObj = obj.get("childNode");
            if (childObj instanceof JSONArray) {
                JSONArray childNode = (JSONArray) childObj;
                if (childNode != null && childNode.length() > 0) {
                    for (int j = 0; j < childNode.length(); j++) {
                        JSONObject child = childNode.getJSONObject(j);

                        OaDepartmentDO childDept = jsonObj2DeptDO(child);
                        dept.getChildNode().add(childDept);
                    }
                }
            }
        }

        return dept;
    }

    private List<SysUser> listOAEmp(String deptId, String workNo) {
        List<SysUser> result = new ArrayList<>();

        int pageNumber = 1;
        boolean hasNext = true;
        try {
            while (hasNext) {
                OaResponse response = this.dhAirOaApiService.queryEmpDepList("", deptId, workNo, "", "", pageNumber);
                Object data = response.getData();
                if (data != null && data instanceof JSONArray) {
                    JSONArray datas = (JSONArray) data;
                    for (int i = 0; i < datas.length(); i++) {
                        JSONObject jsObj = datas.getJSONObject(i);

                        SysUser sysUser = new SysUser();
                        if (jsObj.has("workNo") && jsObj.get("workNo") != null) {
                            sysUser.setWorkNo(jsObj.getString("workNo"));
                        }
                        if (jsObj.has("name") && jsObj.get("name") != null) {
                            sysUser.setUserName(jsObj.getString("name"));
                        }
                        if (jsObj.has("deptId") && jsObj.get("deptId") != null) {
                            sysUser.setdeptId(jsObj.getString("deptId"));
                        }
                        if (jsObj.has("depts") && jsObj.get("depts") != null) {
                            sysUser.setDeptName(jsObj.getString("depts"));
                        }
                        if (jsObj.has("mobileNumber") && jsObj.get("mobileNumber") != null) {
                            sysUser.setUserPhone(jsObj.getString("mobileNumber"));
                        }
                        if (jsObj.has("workEmail") && jsObj.get("workEmail") != null) {
                            sysUser.setUserMail(jsObj.getString("workEmail"));
                        }
                        sysUser.setId(UUID.randomUUID().toString());
                        sysUser.setUserType(0);
                        sysUser.setUserSource("来自OA");
                        sysUser.setStatus(1);
                        result.add(sysUser);
                    }
                } else {
                    break;
                }
                if (response.getTotalSize() != null) {
                    int totalSize = response.getTotalSize().intValue();
                    if (totalSize <= pageNumber * 50) {
                        hasNext = false;
                    } else {
                        hasNext = true;
                        pageNumber++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/
}
